(function($) {
  function onPageCreate(e, document, window) {
    var $page = $(this);
    
    var $toolbar = $page.find('div.jfJQMToolbar');
    $toolbar.find('.enabler').bind('vclick', onEnablerClick);
    $toolbar.find('.zoomIn').bind('vclick', onZoomInClick);
    $toolbar.find('.zoomOut').bind('vclick', onZoomOutClick);
    $toolbar.find('.reload').bind('vclick', onReloadClick);
  }
  
  function onZoomInClick() {
    alterZoomLevel(1);
  }
  function onZoomOutClick() {
    alterZoomLevel(-1);
  }
  function onReloadClick(e) {
    
    if (window.jfPD) {
      window.jfPD.controller.reloadPage();
      return;
    }
  
    $.mobile.showPageLoadingMsg();
    var fragment = $.mobile.path.stripHash(location.hash);
    if (fragment && fragment.length && !window.PhoneGap) {
      window.location.href = fragment;
    }
    else {
      window.location.reload();
    }
  }
  
  function onEnablerClick(e) {
    var $enabler = $(this);
    var $content = $enabler.next('.content');
    $content.toggle('fast');
  }
  
  function alterZoomLevel(changeValue) {
    var $html = $('html');
    var zoomLevel = $html.attr('data-jfPD_zoom');
    if (!zoomLevel) {
      zoomLevel = 0;
    }
    
    if (zoomLevel > 0) {
      $html.removeClass('jfPD_zoom'+zoomLevel);
    }

    zoomLevel = parseInt(zoomLevel) + changeValue;
    zoomLevel = Math.max(0, zoomLevel);
    zoomLevel = Math.min(3, zoomLevel);
    
    $html[zoomLevel > 0 ? 'addClass' : 'removeClass']('jfPD_zoom');
    $html.attr('data-jfPD_zoom', zoomLevel);
    $html.addClass('jfPD_zoom'+zoomLevel);
  }
  
  $("div:jqmData(role='page')").live('pagecreate', onPageCreate);
  
})(jQuery, document, window);
